package com.guodi.model.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.AjaxResult;
import com.guodi.common.utils.PageData;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.model.entity.ApiIdtIndicatorsDir;
import com.guodi.model.entity.IdtIndicators;
import com.guodi.model.entity.IdtIndicatorsType;
import com.guodi.model.entity.IdtTargetValue;
import com.guodi.model.service.*;
import com.guodi.model.utils.ConvertUtil;
import com.guodi.model.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @描述：指标目标值表控制类
 * @作者: 彭辉
 * @日期: 2020-06-05
 */
@RestController
@RequestMapping("/IdtTargetValue")
@Api(value = "API - IdtTargetValueController", tags = "指标目标值表")
public class IdtTargetValueController extends BaseController {

    @Resource
    public IIdtTargetValueService idtTargetValueService;

    @Resource
    public IIdtIndicatorsService iIdtIndicatorsService;

    @Resource
    public IIdtReportValueService iIdtReportValueService;

    @Resource
    private IIdtIndicatorsDirService iIdtIndicatorsDirService;

    @Resource
    private IIdtIndicatorsTypeService iIdtIndicatorsTypeService;

    @Resource
    private IIdtMonitorValueService iIdtMonitorValueService;

    /**
     * @描述: 根据实体属性分页查询
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020-06-05
     **/
    @PostMapping("/listByKeyWord")
    @ApiOperation(value = " 根据关键字进行查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "long", paramType = "query", example = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示数量", required = true, dataType = "long", paramType = "query", example = "10"),
            @ApiImplicitParam(name = "keyWord", value = "关键字搜索", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份搜索", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortWay", value = "排序方式", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划代码", dataType = "string", paramType = "query")
    })
    public AjaxResult listByKeyWord(@ApiIgnore Page page, String keyWord, String year, String sort, String sortWay, String divisionCode) {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该用户所属部门不存在");
        }
        String orgId = deptId;
        HashMap map = new HashMap();
        Long start = (page.getCurrent() - 1) * page.getSize();
        Integer yearNum = null;
        if (StringUtils.isNotBlank(year)) {
            yearNum = Integer.valueOf(year);
        }
        List<IdtTargetValue> idtTargetValueList = idtTargetValueService.listByKeyWord(keyWord, yearNum, page.getSize(), start, sort, sortWay, divisionCode, orgId);
        //设置行政区划名称
        for (int i = 0; i < idtTargetValueList.size(); i++) {
            String divisionName = idtTargetValueService.getNameByDivisionCode(idtTargetValueList.get(i).getDivisionCode());
            idtTargetValueList.get(i).setDivisionName(divisionName);
        }
        Integer selectCount = idtTargetValueService.listByKeyWordAndCodeCount(keyWord, yearNum, divisionCode, orgId);
        map.put("records", idtTargetValueList);
        map.put("total", selectCount);
        map.put("size", page.getSize());
        map.put("current", page.getCurrent());
        map.put("searchCount", true);
        map.put("pages", selectCount % page.getSize() == 0 ? selectCount / page.getSize() : selectCount / page.getSize() + 1);
        return new AjaxResult(map);
    }

    /**
     * @描述: 根据主键查询
     * @入参:
     * @出参:
     * @作者: 彭辉
     * @日期: 2020-06-05
     **/
    @PostMapping("/findById")
    @ApiOperation(value = "根据主键查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public AjaxResult findById(String id) {
        if (StringUtils.isBlank(id)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "id不能为空");
        }
        IdtTargetValue idtTargetValue = idtTargetValueService.getById(id);
        return new AjaxResult(idtTargetValue);
    }

    /**
     * @描述: 新增
     * @入参:
     * @出参:
     * @作者: 彭辉
     * @日期: 2020-06-05
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "monitorValue", value = "监测值", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "gatherTime", value = "采集时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "warnStatus", value = "预警状态", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "indicatorsId", value = "指标id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "explain", value = "指标说明", required = false, dataType = "string", paramType = "query"),
    })
    public AjaxResult save(IdtTargetValue idtTargetValue) {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该用户所属部门不存在");
        }
        //相同指标不允许添加相同的监测年份
        LambdaQueryWrapper<IdtTargetValue> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(IdtTargetValue::getIndicatorsId, idtTargetValue.getIndicatorsId());
        queryWrapper.eq(IdtTargetValue::getTargetYear, idtTargetValue.getTargetYear());
        queryWrapper.eq(IdtTargetValue::getDivisionCode, idtTargetValue.getDivisionCode());
        List<IdtTargetValue> list = idtTargetValueService.list(queryWrapper);
        if (list.size() > 0) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该指标所处年份、行政区划规划目标值已存在");
        }
        prepareData(idtTargetValue, true);
        // 处理行政区划代码位数问题
        // 注：2021-04-28 11:19:00去除行政区划代码补充00
//        idtTargetValue.setDivisionCode(idtTargetValue.getDivisionCode().length() == 2 ? idtTargetValue.getDivisionCode() + "0000" : idtTargetValue.getDivisionCode().length() == 4 ? idtTargetValue.getDivisionCode() + "00" : idtTargetValue.getDivisionCode());
        idtTargetValue.setId(UuidUtil.get32UUID());
        String divisionName = idtTargetValueService.getNameByDivisionCode(idtTargetValue.getDivisionCode());
        idtTargetValue.setDivisionName(divisionName);
        //关联指标信息
        IdtIndicators idtIndicators = iIdtIndicatorsService.getById(idtTargetValue.getIndicatorsId());
        if (idtIndicators != null) {
            idtTargetValue.setIdtCode(idtIndicators.getCode());
            idtTargetValue.setIdtName(idtIndicators.getName());
            idtTargetValue.setIdtUnit(idtIndicators.getUnit());
        }
        idtTargetValue.setId(UuidUtil.get32UUID());
        idtTargetValue.setOrgId(deptId);
        idtTargetValueService.save(idtTargetValue);
        //修改规划值时，同步更新监测值的预警字段
        iIdtMonitorValueService.updateWarnStatus(idtTargetValue.getIndicatorsId(), idtTargetValue.getDivisionCode(), idtTargetValue.getTargetYear()+"", idtTargetValue.getTargetValue());
        iIdtReportValueService.updateStandard(idtTargetValue.getIndicatorsId(),idtTargetValue.getDivisionCode(),idtTargetValue.getTargetYear()+"",idtTargetValue.getTargetValue());
        return new AjaxResult(idtTargetValue);
    }

    /**
     * @描述: 修改
     * @入参:
     * @出参:
     * @作者: 彭辉
     * @日期: 2020-06-05
     **/
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public AjaxResult update(IdtTargetValue idtTargetValue) {
        //相同指标不允许添加相同的监测年份
        LambdaQueryWrapper<IdtTargetValue> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(IdtTargetValue::getIndicatorsId, idtTargetValue.getIndicatorsId());
        queryWrapper.eq(IdtTargetValue::getTargetYear, idtTargetValue.getTargetYear());
        queryWrapper.eq(IdtTargetValue::getDivisionCode, idtTargetValue.getDivisionCode());
        queryWrapper.ne(IdtTargetValue::getId, idtTargetValue.getId());
        List<IdtTargetValue> list = idtTargetValueService.list(queryWrapper);
        if (list.size() > 0) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该指标所处年份、行政区划规划目标值已存在");
        }
        prepareData(idtTargetValue, false);
        idtTargetValueService.updateById(idtTargetValue);
        //修改规划值时，同步更新监测值的预警字段
        iIdtMonitorValueService.updateWarnStatus(idtTargetValue.getIndicatorsId(), idtTargetValue.getDivisionCode(), idtTargetValue.getTargetYear()+"", idtTargetValue.getTargetValue());
        iIdtReportValueService.updateStandard(idtTargetValue.getIndicatorsId(),idtTargetValue.getDivisionCode(),idtTargetValue.getTargetYear()+"",idtTargetValue.getTargetValue());
        return new AjaxResult(idtTargetValue);
    }

    /**
     * @描述: 根据主键删除
     * @入参: id
     * @出参:
     * @作者: 彭辉
     * @日期: 2020-06-05
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据主键删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public AjaxResult delete(String id) {
        IdtTargetValue idtTargetValue = idtTargetValueService.getById(id);
        idtTargetValueService.removeById(id);
        //删除规划值时，同步更新监测值的预警字段
        iIdtMonitorValueService.updateWarnStatus(idtTargetValue.getIndicatorsId(), idtTargetValue.getDivisionCode(), idtTargetValue.getTargetYear()+"", null);
        //删除规划值时将该规划值对应的所有上报知道的达标字段修改为空
        iIdtReportValueService.updateStandard(idtTargetValue.getIndicatorsId(),idtTargetValue.getDivisionCode(),idtTargetValue.getTargetYear()+"",null);
        return new AjaxResult();
    }

    /**
     * @描述:删除多条记录
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/15 16:55
     **/
    @PostMapping("/deleteByIds")
    @ApiOperation(value = "根据多个id删除,多个id用,隔开")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public AjaxResult deleteByIds(String ids) {
        String[] idsAry = ids.split(",");
        List<String> idList = Arrays.asList(idsAry);
        Collection<IdtTargetValue> idtTargetValues = idtTargetValueService.listByIds(idList);
        idtTargetValueService.removeByIds(idList);
        for (IdtTargetValue idtTargetValue: idtTargetValues) {
            //删除规划值时，同步更新监测值的预警字段
            iIdtMonitorValueService.updateWarnStatus(idtTargetValue.getIndicatorsId(), idtTargetValue.getDivisionCode(), idtTargetValue.getTargetYear()+"", null);
            //删除规划值时将该规划值对应的所有上报知道的达标字段修改为空
            iIdtReportValueService.updateStandard(idtTargetValue.getIndicatorsId(),idtTargetValue.getDivisionCode(),idtTargetValue.getTargetYear()+"",null);
        }

        return new AjaxResult();
    }

    /**
     * @描述:判断重复数据
     * @入参:
     * @出参:
     * @作者: 郑文彬
     * @日期: 2020/8/28 15:11
     **/
    @PostMapping("/isExistsTarget")
    @ApiOperation(value = "判断重复数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isCheck", value = "是否为指标填报(默认否)", required = false, dataType = "Boolean", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "指标体系编码，isCheck为true时必填", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "particularYear", value = "指标体系年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "区域编码（查询指标数值时需要传）", dataType = "string", paramType = "query")
    })
    public AjaxResult isExistsTarget(MultipartFile multipartFile, String code, Boolean isCheck, String orgId, String particularYear, String divisionCode) throws Exception {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "改用户所属部门不存在");
        }
        if (multipartFile.isEmpty()) {
            new AjaxResult(StatusCode.ERROR_CODE_40005, "导入文件不能为空！");
        }
        // 根据上传MultipartFile对象获取excel数据集
        List<List<String>> excelList = ExcelUtil.getExcelData(multipartFile);
        if (excelList == null || excelList.size() <= 1) {
            new AjaxResult(StatusCode.ERROR_CODE_40005, "导入文件数据为空！");
        }
        // 去除数据的前后空格
        excelList.stream().forEach(rowList->{
            for(int i = 0; i < rowList.size(); i++) {
                if(rowList.get(i) == null){
                    rowList.set(i,"");
                }else{
                    rowList.set(i,rowList.get(i).trim());
                }
            }
            // 去除指标编码的小数点
            int idtCodeIndex = 0;
            if (rowList.get(idtCodeIndex).contains(".")){
                rowList.set(idtCodeIndex, rowList.get(idtCodeIndex).substring(0, rowList.get(idtCodeIndex).indexOf(".") ));
            }
            // 去除行政区划编码的小数点
            int divisionCodeIndex = 4;
            if (rowList.get(divisionCodeIndex).contains(".")){
                rowList.set(divisionCodeIndex, rowList.get(divisionCodeIndex).substring(0, rowList.get(divisionCodeIndex).indexOf(".") ));
            }
            // 去除年份的小数点
            int baseYearIndex = 5;
            if (rowList.get(baseYearIndex).contains(".")){
                rowList.set(baseYearIndex, rowList.get(baseYearIndex).substring(0, rowList.get(baseYearIndex).indexOf(".") ));
            }
            int targetYearIndex = 7;
            if (rowList.get(targetYearIndex).contains(".")){
                rowList.set(targetYearIndex, rowList.get(targetYearIndex).substring(0, rowList.get(targetYearIndex).indexOf(".") ));
            }
        });
        // 查询指标填报中指标数据
        List<String> indicatorsIds = new ArrayList<>();
        if(null != isCheck && isCheck){
            // 暂时写死
            IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(code, particularYear, divisionCode);
            if(null != one){
                List<ApiIdtIndicatorsDir> treeList = iIdtIndicatorsDirService.listDirByCode(one.getId(), null,null);
                indicatorsIds = treeList.stream().filter(x -> x.getType()==2).map(x -> x.getIndicatorsId()).collect(Collectors.toList());
            }
        }
        // 重复数据
        List<IdtTargetValue> repeatingData = new ArrayList<>();
        for (int i = 1; i < excelList.size(); i++) {
            List<String> dataList = excelList.get(i);
            String idtCode = dataList.get(0);
            LambdaQueryWrapper<IdtIndicators> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.eq(IdtIndicators::getCode, idtCode);
            IdtIndicators idtIndicators = iIdtIndicatorsService.getOne(queryWrapper);
            IdtTargetValue idtTargetValue = new IdtTargetValue();
            String targetYear = dataList.get(7).indexOf(".") >= 0 ? dataList.get(7).substring(0, dataList.get(7).indexOf(".")) : dataList.get(7);
            String baseYear = dataList.get(5).indexOf(".") >= 0 ? dataList.get(5).substring(0, dataList.get(5).indexOf(".")) : dataList.get(5);
            idtTargetValue.setBaseYear(baseYear);
            idtTargetValue.setDivisionCode(dataList.get(4));
            idtTargetValue.setIdtCode(idtCode);
            if(StringUtils.isNotBlank(dataList.get(4)) && dataList.get(4).indexOf(".") != -1){
                //可能读成数字了，带小数，去掉小数
                String[] str =  dataList.get(4).split("\\.");
                idtTargetValue.setDivisionCode(str[0]);
            }
            idtTargetValue.setBaseValue(dataList.get(6));
            idtTargetValue.setTargetYear(Integer.parseInt(targetYear));
            idtTargetValue.setTargetValue(dataList.get(8));
            idtTargetValue.setId(UuidUtil.get32UUID());
            idtTargetValue.setOrgId(deptId);
            idtTargetValue.setDivisionName(dataList.get(3));
            if (idtIndicators != null) {
                //判断是否存在相同指标id与行政区划编码与相同年份
                LambdaQueryWrapper<IdtTargetValue> queryWrapper1 = new QueryWrapper().lambda();
                queryWrapper1.eq(IdtTargetValue::getTargetYear, idtTargetValue.getTargetYear());
                queryWrapper1.eq(IdtTargetValue::getDivisionCode, idtTargetValue.getDivisionCode());
                queryWrapper1.eq(IdtTargetValue::getIndicatorsId, idtIndicators.getId());
                List<IdtTargetValue> sourceIdtTargetValueList = idtTargetValueService.list(queryWrapper1);
                if(null != isCheck && isCheck){
                    if(indicatorsIds.contains(idtIndicators.getId())){
                        if (sourceIdtTargetValueList.size() > 0) {
                            repeatingData.add(idtTargetValue);
                        }
                    }
                }else {
                    if (sourceIdtTargetValueList.size() > 0) {
                        repeatingData.add(idtTargetValue);
                    }
                }
            }
        }
        String resultCodes = "";
        for (IdtTargetValue obj : repeatingData) {
            if (!resultCodes.contains(obj.getIdtCode())) {
                resultCodes += StringUtils.isBlank(resultCodes) ? obj.getIdtCode() : "," + obj.getIdtCode();
            }
        }
        return new AjaxResult(resultCodes);
    }

    /**
     * @描述:导入Excel
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/15 19:03
     **/
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isUpdate", value = "当同一指标同一地区同一更新周期已经有记录时，是否更新已存在记录，true-更新记录，false-跳过记录（默认false）", required = false, dataType = "Boolean", paramType = "query"),
            @ApiImplicitParam(name = "isCheck", value = "是否为指标填报(默认否)", required = false, dataType = "Boolean", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "指标体系编码，isCheck为true时必填", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "particularYear", value = "指标体系年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "区域编码（查询指标数值时需要传）", dataType = "string", paramType = "query")
    })
    public AjaxResult importExcel(MultipartFile multipartFile, Boolean isUpdate, Boolean isCheck, String code, String orgId, String particularYear, String divisionCode) {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "改用户所属部门不存在");
        }
        if (multipartFile.isEmpty()) {
            new AjaxResult(StatusCode.ERROR_CODE_40005, "导入文件不能为空！");
        }
        // 根据上传MultipartFile对象获取excel数据集
        List<List<String>> excelList = ExcelUtil.getExcelData(multipartFile);
        if (excelList == null || excelList.size() <= 1) {
            new AjaxResult(StatusCode.ERROR_CODE_40005, "导入文件数据为空！");
        }

        excelList.stream().forEach(rowList->{
            // 去除数据的前后空格
            for(int i = 0; i < rowList.size(); i++) {
                if(rowList.get(i) == null){
                    rowList.set(i,"");
                }else{
                    rowList.set(i,rowList.get(i).trim());
                }
            }
            // 去除指标编码的小数点
            int idtCodeIndex = 0;
            if (rowList.get(idtCodeIndex).contains(".")){
                rowList.set(idtCodeIndex, rowList.get(idtCodeIndex).substring(0, rowList.get(idtCodeIndex).indexOf(".") ));
            }
            // 去除行政区划编码的小数点
            int divisionCodeIndex = 4;
            if (rowList.get(divisionCodeIndex).contains(".")){
                rowList.set(divisionCodeIndex, rowList.get(divisionCodeIndex).substring(0, rowList.get(divisionCodeIndex).indexOf(".") ));
            }
            // 去除年份的小数点
            int baseYearIndex = 5;
            if (rowList.get(baseYearIndex).contains(".")){
                rowList.set(baseYearIndex, rowList.get(baseYearIndex).substring(0, rowList.get(baseYearIndex).indexOf(".") ));
            }
            int targetYearIndex = 7;
            if (rowList.get(targetYearIndex).contains(".")){
                rowList.set(targetYearIndex, rowList.get(targetYearIndex).substring(0, rowList.get(targetYearIndex).indexOf(".") ));
            }
        });
        List<String> indicatorsIds = new ArrayList<>();
        if(null != isCheck && isCheck){
            // 暂时写死
            IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(code, particularYear, divisionCode);
            if(null != one){
                List<ApiIdtIndicatorsDir> treeList = iIdtIndicatorsDirService.listDirByCode(one.getId(), null,null);
                indicatorsIds = treeList.stream().filter(x -> x.getType()==2).map(x -> x.getIndicatorsId()).collect(Collectors.toList());
            }
        }
        // 存储新增、更新指标集合
        List<IdtTargetValue> saveUpdateList = new ArrayList<>();
        for (int i = 1; i < excelList.size(); i++) {
            List<String> dataList = excelList.get(i);
            String idtCode = dataList.get(0);
            LambdaQueryWrapper<IdtIndicators> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.eq(IdtIndicators::getCode, idtCode);
            List<IdtIndicators> idtList = iIdtIndicatorsService.list(queryWrapper);
            if (idtList == null || idtList.size() < 1) {
                continue;
            }
            IdtIndicators idtIndicators = idtList.get(0);
            IdtTargetValue idtTargetValue = new IdtTargetValue();
            String targetYear = dataList.get(7).indexOf(".") >= 0 ? dataList.get(7).substring(0, dataList.get(7).indexOf(".")) : dataList.get(7);
            String baseYear = dataList.get(5).indexOf(".") >= 0 ? dataList.get(5).substring(0, dataList.get(5).indexOf(".")) : dataList.get(5);
            idtTargetValue.setBaseYear(baseYear);
            idtTargetValue.setDivisionCode(dataList.get(4));
            if(StringUtils.isNotBlank(dataList.get(4)) && dataList.get(4).indexOf(".") != -1){
                //可能读成数字了，带小数，去掉小数
                String[] str =  dataList.get(4).split("\\.");
                idtTargetValue.setDivisionCode(str[0]);
            }
            idtTargetValue.setBaseValue(dataList.get(6));
            idtTargetValue.setTargetYear(Integer.parseInt(targetYear));
            idtTargetValue.setTargetValue(dataList.get(8));
            // 做非空及数字校验
            if(StringUtils.isNotBlank(dataList.get(8))){
                Boolean isNum = ConvertUtil.isNumeric(dataList.get(8));
                if (!isNum) {
                    return new AjaxResult(StatusCode.ERROR_CODE_40005, "第"+(i+1)+"行规划目标值不正确，请检查");
                }
            }
            idtTargetValue.setExplain(dataList.get(9));
            idtTargetValue.setId(UuidUtil.get32UUID());
            idtTargetValue.setOrgId(deptId);
            idtTargetValue.setDivisionName(dataList.get(3));
            if (idtIndicators != null) {
                //判断是否存在相同指标id与行政区划编码与相同年份
                LambdaQueryWrapper<IdtTargetValue> queryWrapper1 = new QueryWrapper().lambda();
                queryWrapper1.eq(IdtTargetValue::getTargetYear, Integer.parseInt(targetYear));
                queryWrapper1.eq(IdtTargetValue::getDivisionCode, idtTargetValue.getDivisionCode());
                queryWrapper1.eq(IdtTargetValue::getIndicatorsId, idtIndicators.getId());
                List<IdtTargetValue> sourceIdtTargetValueList = idtTargetValueService.list(queryWrapper1);
                if (sourceIdtTargetValueList.size() > 0) {
                    if(isUpdate != null && isUpdate){
                        IdtTargetValue targetValue = sourceIdtTargetValueList.get(0);
                        targetValue.setTargetValue(idtTargetValue.getTargetValue());
                        targetValue.setBaseYear(idtTargetValue.getBaseYear());
                        targetValue.setBaseValue(idtTargetValue.getBaseValue());
                        targetValue.setExplain(idtTargetValue.getExplain());
                        idtTargetValue = targetValue;
                    }else{
                        continue;
                    }
                }
                idtTargetValue.setIndicatorsId(idtIndicators.getId());
                idtTargetValue.setIdtCode(idtIndicators.getCode());
                idtTargetValue.setIdtName(idtIndicators.getName());
                idtTargetValue.setIdtUnit(idtIndicators.getUnit());
                prepareData(idtTargetValue, true);
                if(null != isCheck && isCheck){
                    if(indicatorsIds.contains(idtIndicators.getId())){
                        saveUpdateList.add(idtTargetValue);
                    }
                }else {
                    saveUpdateList.add(idtTargetValue);
                }
            }
        }
        if (saveUpdateList.size() > 0) {
            // 批量保存更新
            idtTargetValueService.saveOrUpdateBatch(saveUpdateList);
            for (IdtTargetValue idtTargetValue: saveUpdateList) {
                //同步更新监测值的预警字段
                iIdtMonitorValueService.updateWarnStatus(idtTargetValue.getIndicatorsId(), idtTargetValue.getDivisionCode(), idtTargetValue.getTargetYear()+"", idtTargetValue.getTargetValue());
                iIdtReportValueService.updateStandard(idtTargetValue.getIndicatorsId(),idtTargetValue.getDivisionCode(),idtTargetValue.getTargetYear()+"",idtTargetValue.getTargetValue());
            }
        }
        return new AjaxResult(saveUpdateList);
    }

    /**
    * @描述: 导入Json文件
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/11/4 16:30
    **/
    @PostMapping("/exportJson")
    @ApiOperation(value = "导入Json文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "指标体系编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "机构id(65fc1451aa4640c795b971ae9199456c)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "particularYear", value = "指标体系年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "区域编码（查询指标数值时需要传）", dataType = "string", paramType = "query")
    })
    public AjaxResult exportJson(MultipartFile multipartFile, String code, String orgId, String particularYear, String divisionCode) throws Exception{
        Reader reader = new InputStreamReader(multipartFile.getInputStream(),"utf-8");
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
        reader.close();
        String jsonStr = sb.toString();
        List<IdtTargetValue> list = JSONObject.parseArray(jsonStr, IdtTargetValue.class);
        List<IdtTargetValue> addIdtTargetValueList = new ArrayList<>();
        List<IdtTargetValue> updateIdtTargetValueList =  new ArrayList<>();
        if(null == list || list.size() == 0){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"参数格式错误，请检查");
        }
        // 数据筛选 只针对于现状评估的指标数据
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(code, particularYear, divisionCode);
        if(null == one){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"该年份/行政区划暂未配置指标体系");
        }
        List<ApiIdtIndicatorsDir> treeList = iIdtIndicatorsDirService.listDirByCode(one.getId(), orgId,null);
        List<String> indicatorsIds = treeList.stream().filter(x -> x.getType()==2).map(x -> x.getIndicatorsId()).collect(Collectors.toList());
        for (IdtTargetValue idtTargetValue: list) {
            //相同指标不允许添加相同的监测年份-做更新处理
            LambdaQueryWrapper<IdtTargetValue> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.eq(IdtTargetValue::getIndicatorsId, idtTargetValue.getIndicatorsId());
            queryWrapper.eq(IdtTargetValue::getTargetYear, idtTargetValue.getTargetYear());
            queryWrapper.eq(IdtTargetValue::getDivisionCode, idtTargetValue.getDivisionCode());
            List<IdtTargetValue> idtTargetValues = idtTargetValueService.list(queryWrapper);
            if(indicatorsIds.contains(idtTargetValue.getIndicatorsId())){
                if (idtTargetValues.size() > 0) {
                    IdtTargetValue idtTargetValue1 = idtTargetValues.get(0);
                    idtTargetValue1.setTargetValue(idtTargetValue.getTargetValue());
                    prepareData(idtTargetValue1,false);
                    updateIdtTargetValueList.add(idtTargetValue1);
                }else {
                    idtTargetValue.setId(UuidUtil.get32UUID());
                    prepareData(idtTargetValue,true);
                    addIdtTargetValueList.add(idtTargetValue);
                }
            }
        }
        if(addIdtTargetValueList.size() > 0){
            idtTargetValueService.saveBatch(addIdtTargetValueList);
            for (IdtTargetValue idtTargetValue: addIdtTargetValueList) {
                //同步更新监测值的预警字段
                iIdtMonitorValueService.updateWarnStatus(idtTargetValue.getIndicatorsId(), idtTargetValue.getDivisionCode(), idtTargetValue.getTargetYear()+"", idtTargetValue.getTargetValue());
                iIdtReportValueService.updateStandard(idtTargetValue.getIndicatorsId(),idtTargetValue.getDivisionCode(),idtTargetValue.getTargetYear()+"",idtTargetValue.getTargetValue());
            }
        }
        if(updateIdtTargetValueList.size() > 0){
            idtTargetValueService.updateBatchById(updateIdtTargetValueList);
            for (IdtTargetValue idtTargetValue: updateIdtTargetValueList) {
                //同步更新监测值的预警字段
                iIdtMonitorValueService.updateWarnStatus(idtTargetValue.getIndicatorsId(), idtTargetValue.getDivisionCode(), idtTargetValue.getTargetYear()+"", idtTargetValue.getTargetValue());
                iIdtReportValueService.updateStandard(idtTargetValue.getIndicatorsId(),idtTargetValue.getDivisionCode(),idtTargetValue.getTargetYear()+"",idtTargetValue.getTargetValue());
            }
        }
        return new AjaxResult();
    }

    /**
     * @描述:导出Excel
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/18 10:20
     **/
    @PostMapping("/exportExcel")
    @ApiOperation(value = "导出指标Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "exportType", value = "导出类型,传入all默认导出全部,否则根据,分隔删除", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "ids", value = "导出指标id集合", required = false, dataType = "string", paramType = "query")
    })
    public void exportExcel(String exportType, String ids) {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return;
        }
        String orgId = deptId;
        List<IdtTargetValue> list;
        //查询指标信息子项信息
        List<IdtIndicators> idtIndicatorsList;
        List<String> stringIdList = new ArrayList<>();
        if ("all".equals(exportType)) {
            // 导出所有指标
            LambdaQueryWrapper<IdtTargetValue> queryWrapper = new QueryWrapper().lambda();
            // 因为查看时，没有和机构挂钩，故导出时导出所有。 2020-12-31 汤厚韬
            // queryWrapper.eq(IdtTargetValue::getOrgId, orgId);
            list = idtTargetValueService.list(queryWrapper);
        } else {
            List<String> idsList = Arrays.asList(ids.split(","));
            // 导出选中指标
            list = (List<IdtTargetValue>) idtTargetValueService.listByIds(idsList);
        }
        for (int z = 0; z < list.size(); z++) {
            stringIdList.add(list.get(z).getIndicatorsId());
        }
        //指标子项信息
        idtIndicatorsList = (List<IdtIndicators>) iIdtIndicatorsService.list();
        //赋值指标相关子项信息
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < idtIndicatorsList.size(); j++) {
                if (list.get(i).getIndicatorsId().equals(idtIndicatorsList.get(j).getId())) {
                    IdtIndicators idtIndicators = idtIndicatorsList.get(j);
                    list.get(i).setIdtUnit(idtIndicators.getUnit());
                    list.get(i).setIdtName(idtIndicators.getName());
                    list.get(i).setIdtCode(idtIndicators.getCode());
                    String divisionName = idtTargetValueService.getNameByDivisionCode(list.get(i).getDivisionCode());
                    list.get(i).setDivisionName(divisionName);
                }
            }
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        for (int i = 0; i < list.size(); i++) {
            IdtTargetValue idtTargetValue = list.get(i);
            Object[] datas = new Object[9];
            datas[0] = idtTargetValue.getIdtCode();
            datas[1] = idtTargetValue.getIdtName();
            datas[2] = idtTargetValue.getIdtUnit();
            datas[3] = idtTargetValue.getDivisionName();
            datas[4] = idtTargetValue.getDivisionCode();
            datas[5] = idtTargetValue.getBaseYear();
            datas[6] = idtTargetValue.getBaseValue();
            datas[7] = idtTargetValue.getTargetYear().toString();
            datas[8] = idtTargetValue.getTargetValue();
            dataList.add(datas);
        }
        // 导出Excel
        String[] titles = {"指标编号", "指标名称", "单位", "行政区划名称", "行政区划代码", "基期年", "基期值", "规划目标年", "规划目标值"};
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        ExcelUtil.exportExcel(response, "规划指标", "规划指标信息", titles, dataList);
    }

    /**
     * @描述: 批量保存指标目标值
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020/7/7 14:20
     **/
    @PostMapping("/savaMulTargetValue")
    @ApiOperation(value = "批量保存指标目标值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "formJson", value = "存放指标对象的json字符串", required = true, dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult savaMulTargetValue(String formJson){
        List<IdtTargetValue> list = JSONObject.parseArray(formJson, IdtTargetValue.class);
        List<IdtTargetValue> addIdtTargetValueList = new ArrayList<>();
        List<IdtTargetValue> updateIdtTargetValueList =  new ArrayList<>();
        if(null == list || list.size() == 0){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"参数格式错误，请检查");
        }
        // 检查有没有规划年没传回的
        LinkedList<String> noTargetYearIdtNameList = new LinkedList<>();
        for(IdtTargetValue idtTargetValue : list) {
            if (idtTargetValue.getTargetYear() == null) {
                noTargetYearIdtNameList.add(idtTargetValue.getIdtName());
            }
        }
        if (!noTargetYearIdtNameList.isEmpty()) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"如下指标未设置对应的指标对标配置：" + noTargetYearIdtNameList.stream().collect(Collectors.joining("，")));
        }
        for (IdtTargetValue idtTargetValue: list) {
            //相同指标不允许添加相同的监测年份-做更新处理
            LambdaQueryWrapper<IdtTargetValue> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.eq(IdtTargetValue::getIndicatorsId, idtTargetValue.getIndicatorsId());
            queryWrapper.eq(IdtTargetValue::getTargetYear, idtTargetValue.getTargetYear());
            queryWrapper.eq(IdtTargetValue::getDivisionCode, idtTargetValue.getDivisionCode());
            List<IdtTargetValue> idtTargetValues = idtTargetValueService.list(queryWrapper);
            if (idtTargetValues.size() > 0) {
                IdtTargetValue idtTargetValue1 = idtTargetValues.get(0);
                idtTargetValue1.setTargetValue(idtTargetValue.getTargetValue());
                prepareData(idtTargetValue1,false);
                updateIdtTargetValueList.add(idtTargetValue1);
            }else {
                idtTargetValue.setId(UuidUtil.get32UUID());
                prepareData(idtTargetValue,true);
                addIdtTargetValueList.add(idtTargetValue);
            }
        }
        if(addIdtTargetValueList.size() > 0){
            idtTargetValueService.saveBatch(addIdtTargetValueList);
            for (IdtTargetValue idtTargetValue: addIdtTargetValueList) {
                //同步更新监测值的预警字段
                iIdtMonitorValueService.updateWarnStatus(idtTargetValue.getIndicatorsId(), idtTargetValue.getDivisionCode(), idtTargetValue.getTargetYear()+"", idtTargetValue.getTargetValue());
                iIdtReportValueService.updateStandard(idtTargetValue.getIndicatorsId(),idtTargetValue.getDivisionCode(),idtTargetValue.getTargetYear()+"",idtTargetValue.getTargetValue());
            }
        }
        if(updateIdtTargetValueList.size() > 0){
            idtTargetValueService.updateBatchById(updateIdtTargetValueList);
            for (IdtTargetValue idtTargetValue: updateIdtTargetValueList) {
                //同步更新监测值的预警字段
                iIdtMonitorValueService.updateWarnStatus(idtTargetValue.getIndicatorsId(), idtTargetValue.getDivisionCode(), idtTargetValue.getTargetYear()+"", idtTargetValue.getTargetValue());
                iIdtReportValueService.updateStandard(idtTargetValue.getIndicatorsId(),idtTargetValue.getDivisionCode(),idtTargetValue.getTargetYear()+"",idtTargetValue.getTargetValue());
            }
        }
        return new AjaxResult();
    }

    private void prepareData(IdtTargetValue idtTargetValue, boolean isSave) {
        if (isSave) {
            idtTargetValue.setCreator(this.getUser().getUserId().toString());
            idtTargetValue.setCreateTime(new Date());
            //防止误修改
            idtTargetValue.setModifier(null);
            idtTargetValue.setModifyTime(null);
        } else {
            idtTargetValue.setModifier(this.getUser().getUserId().toString());
            idtTargetValue.setModifyTime(new Date());
            //防止误修改
            idtTargetValue.setCreator(null);
            idtTargetValue.setCreateTime(null);
        }
    }

    /**
     * @描述:查询各年份的规划值
     * @入参:
     * @出参:
     * @作者: 郑文彬
     * @日期: 2020/5/11 11:05
     **/
    @PostMapping("/listValueByYears")
    @ApiOperation(value = " 查询某指标各个城市各年份的规划值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "indicatorsId", value = "指标id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "years", value = "年份(多个年份用英文逗号隔开)", required = true, dataType = "string", paramType = "query"),
    })
    public AjaxResult listValueByYears(String indicatorsId, String years) {
        if(StringUtils.isBlank(indicatorsId) || StringUtils.isBlank(years)){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"指标id和查询年份不能为空！");
        }
        PageData pageData = new PageData(this.getRequest());
        List<Object> resultList = new ArrayList<>();
        String[] split = years.split(",");
        pageData.put("years",Arrays.asList(split));
        //查询某指标下各年份各城市的规划值
        LambdaQueryWrapper<IdtTargetValue> lambda = new QueryWrapper().lambda();
        lambda.eq(IdtTargetValue::getIndicatorsId,indicatorsId);
        List<IdtTargetValue> list = idtTargetValueService.list(lambda);
        //根据城市分组
        Map<String, List<IdtTargetValue>> collect = list.stream().collect(Collectors.groupingBy(IdtTargetValue::getDivisionCode));
        Set<String> keys = collect.keySet();
        for (String key :keys) {
            List<IdtTargetValue> idtPlanValues = collect.get(key);
            Map<Integer, IdtTargetValue> yearMap = idtPlanValues.stream().collect(Collectors.toMap(IdtTargetValue::getTargetYear, Function.identity(),(entity1, entity2) -> entity1));
            Map<String, String> map = new HashMap<>();
            map.put("areaCode",key);
            String areaName = iIdtReportValueService.getNameByDivisionCode(key);
            map.put("areaName",areaName);
            for (String year:split) {
                IdtTargetValue idtPlanValue = yearMap.get(Integer.valueOf(year));
                if(idtPlanValue!=null){
                    map.put(year,idtPlanValue.getTargetValue());
                }else {
                    map.put(year,null);
                }
            }
            resultList.add(map);
        }
        return  new AjaxResult(resultList);
    }
}
